const defaultOptions = {
  countDown: 5,
  countDownNumber: 5
};

let intervalHandlers = [];

function start (options) {
  Object.assign(options, defaultOptions);

  intervalHandlers.forEach(handler => clearInterval(handler));
  intervalHandlers.length = 0;

  let handler2 = setInterval(() => {
    let now = new Date();
    let currentWeek = now.getDay();
    let currentHours = now.getHours();
    let currentMinutes = now.getMinutes();

    // 休市处理（周日、周六；每天9点15分前）
    if (currentWeek == 0 || currentWeek == 6 || currentHours < 9 || currentHours > 15) {
      callStepCallback(options.step, { visible: false });

      return;
    }

    // 早、晚间休市细化处理
    if ((currentHours == 9 && currentMinutes < 15) || (currentHours == 15 && currentMinutes > 2)) {
      callStepCallback(options.step, { visible: false });

      return;
    }

    // 午间休市暂停
    if (currentHours == 12 || (currentHours == 11 && currentMinutes > 30)) {
      callStepCallback(options.step, { visible: false });

      return;
    }

    options.countDown = options.countDown - 1;
    callStepCallback(options.step, { visible: true, number: options.countDown });

    if (!options.countDown) {
      options.countDown = options.countDownNumber;

      if (options.done && typeof options.done == 'function') {
        options.done();
      }
    }
  }, 1000);

  intervalHandlers.push(handler2);
}

function stop () {
  intervalHandlers.forEach(handler => clearInterval(handler));
}

function callStepCallback(callback, args) {
  if(callback && typeof callback == 'function') {
    callback(args);
  }
}

export default {
  start,
  stop
}